<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>打印服务测试</title>
    <style>
        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            line-height: 1.6;
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            color: #333;
        }
        h1 {
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
        }
        .container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }
        .card {
            flex: 1;
            min-width: 400px;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        h2 {
            margin-top: 0;
            color: #3498db;
        }
        button {
            background: #3498db;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background 0.3s;
        }
        button:hover {
            background: #2980b9;
        }
        button:disabled {
            background: #95a5a6;
            cursor: not-allowed;
        }
        textarea {
            width: 100%;
            min-height: 150px;
            margin-bottom: 15px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-family: monospace;
            resize: vertical;
        }
        input[type="file"] {
            margin-bottom: 15px;
            width: 100%;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        #connection-status {
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 20px;
            text-align: center;
            font-weight: bold;
        }
        .status-disconnected {
            background: #f8d7da;
            color: #721c24;
        }
        .status-connected {
            background: #d4edda;
            color: #155724;
        }
        .status-connecting {
            background: #fff3cd;
            color: #856404;
        }
        #logs {
            background: #f8f9fa;
            border: 1px solid #eee;
            border-radius: 4px;
            padding: 15px;
            height: 200px;
            overflow-y: auto;
            font-family: monospace;
            margin-top: 20px;
        }
        .log-entry {
            margin-bottom: 5px;
            border-bottom: 1px solid #eee;
            padding-bottom: 5px;
        }
        .timestamp {
            color: #6c757d;
            margin-right: 8px;
        }
        .success {
            color: #28a745;
        }
        .error {
            color: #dc3545;
        }
        .info {
            color: #17a2b8;
        }
    </style>
</head>
<body>
    <h1>打印服务测试工具</h1>
    
    <div id="connection-status" class="status-disconnected">
        状态：未连接
    </div>
    
    <div class="container">
        <div class="card">
            <h2>连接控制</h2>
            <div class="form-group">
                <label for="ws-url">WebSocket URL:</label>
                <input type="text" id="ws-url" value="ws://localhost:8080" style="width: 100%; padding: 8px;">
            </div>
            <button id="connect-btn">连接</button>
            <button id="disconnect-btn" disabled>断开</button>
        </div>
        
        <div class="card">
            <h2>打印PDF</h2>
            <div class="form-group">
                <label for="pdf-file">选择PDF文件:</label>
                <input type="file" id="pdf-file" accept=".pdf">
            </div>
            <button id="send-pdf-btn" disabled>发送PDF打印请求</button>
        </div>
    </div>
    
    <h2>操作日志</h2>
    <div id="logs"></div>
    
    <script>
        // 全局变量
        let ws = null;
        const statusDisplay = document.getElementById('connection-status');
        const connectBtn = document.getElementById('connect-btn');
        const disconnectBtn = document.getElementById('disconnect-btn');
        const sendTextBtn = document.getElementById('send-text-btn');
        const sendPdfBtn = document.getElementById('send-pdf-btn');
        const logsContainer = document.getElementById('logs');
        const wsUrlInput = document.getElementById('ws-url');
        
        // 添加日志
        function addLog(message, type = 'info') {
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry ${type}`;
            
            const now = new Date();
            const timestamp = now.toLocaleTimeString();
            
            logEntry.innerHTML = `<span class="timestamp">[${timestamp}]</span> ${message}`;
            logsContainer.appendChild(logEntry);
            logsContainer.scrollTop = logsContainer.scrollHeight;
        }
        
        // 连接WebSocket
        connectBtn.addEventListener('click', () => {
            const url = wsUrlInput.value.trim();
            if (!url) {
                addLog('错误: URL不能为空', 'error');
                return;
            }
            
            try {
                statusDisplay.className = 'status-connecting';
                statusDisplay.textContent = '状态：正在连接...';
                
                ws = new WebSocket(url);
                
                ws.onopen = () => {
                    statusDisplay.className = 'status-connected';
                    statusDisplay.textContent = '状态：已连接';
                    connectBtn.disabled = true;
                    disconnectBtn.disabled = false;
                    sendTextBtn.disabled = false;
                    sendPdfBtn.disabled = false;
                    addLog(`已成功连接到 ${url}`, 'success');
                };
                
                ws.onclose = (event) => {
                    addLog(`连接已关闭: Code=${event.code}, Reason=${event.reason || '无原因'}`, 'info');
                    resetConnectionState();
                };
                
                ws.onerror = (error) => {
                    addLog('连接错误: ' + (error.message || '未知错误'), 'error');
                    resetConnectionState();
                };
                
                ws.onmessage = (event) => {
                    try {
                        const response = JSON.parse(event.data);
                        addLog(`收到服务器响应: ${JSON.stringify(response)}`, 
                               response.status === 'success' ? 'success' : 'error');
                    } catch (e) {
                        addLog(`收到服务器响应: ${event.data}`, 'info');
                    }
                };
                
            } catch (error) {
                addLog('创建WebSocket连接时出错: ' + error.message, 'error');
                resetConnectionState();
            }
        });
        
        // 断开WebSocket连接
        disconnectBtn.addEventListener('click', () => {
            if (ws) {
                ws.close();
                addLog('已手动断开连接', 'info');
                resetConnectionState();
            }
        });
        
        // 重置连接状态
        function resetConnectionState() {
            statusDisplay.className = 'status-disconnected';
            statusDisplay.textContent = '状态：未连接';
            connectBtn.disabled = false;
            disconnectBtn.disabled = true;
            sendTextBtn.disabled = true;
            sendPdfBtn.disabled = true;
            ws = null;
        }
        
        // 发送文本打印请求
        sendTextBtn.addEventListener('click', () => {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addLog('错误: WebSocket未连接', 'error');
                return;
            }
            
            const textContent = document.getElementById('text-content').value.trim();
            if (!textContent) {
                addLog('错误: 文本内容不能为空', 'error');
                return;
            }
            
            try {
                const payload = {
                    type: 'text',
                    data: textContent
                };
                
                ws.send(JSON.stringify(payload));
                addLog('已发送文本打印请求', 'info');
                
            } catch (error) {
                addLog('发送文本打印请求失败: ' + error.message, 'error');
            }
        });
        
        // 发送PDF打印请求
        sendPdfBtn.addEventListener('click', () => {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addLog('错误: WebSocket未连接', 'error');
                return;
            }
            
            const fileInput = document.getElementById('pdf-file');
            if (!fileInput.files || fileInput.files.length === 0) {
                addLog('错误: 请选择PDF文件', 'error');
                return;
            }
            
            const file = fileInput.files[0];
            if (file.type !== 'application/pdf') {
                addLog('错误: 请选择PDF类型的文件', 'error');
                return;
            }
            
            const reader = new FileReader();
            
            reader.onload = function(event) {
                try {
                    // 获取base64编码的文件内容
                    const base64Data = event.target.result.split(',')[1];
                    
                    const payload = {
                        type: 'pdf',
                        data: base64Data,
                        filename: file.name
                    };
                    
                    ws.send(JSON.stringify(payload));
                    addLog(`已发送PDF打印请求: ${file.name} (${Math.round(file.size / 1024)} KB)`, 'info');
                    
                } catch (error) {
                    addLog('发送PDF打印请求失败: ' + error.message, 'error');
                }
            };
            
            reader.onerror = function() {
                addLog('读取PDF文件失败', 'error');
            };
            
            // 开始读取文件
            reader.readAsDataURL(file);
            addLog('正在读取PDF文件...', 'info');
        });
        
        // 页面加载时添加初始日志
        window.addEventListener('load', () => {
            addLog('测试工具已准备就绪', 'info');
            addLog('使用说明: 先连接WebSocket，然后发送文本或PDF打印请求', 'info');
        });
    </script>
</body>
</html>
